// pages/home/index.js
import { getRemindRecordToDay, clockIn } from '../../api/user';
const formatTimeUnit = (value) => (value < 10 ? `0${value}` : `${value}`)
const app = getApp();

Page({
  data: {
    isAuthorized: false,
    unreadCount: 2,
    showReminder: false,
    showMissModal: false,
    currentReminderTime: '',
    missInput: '',
    missMedicineId: null,
    // medicines: [
    //   { id: 1, time: '08:00', name: '阿司匹林肠溶片', dose: '100mg/片 × 1片 餐后服用', remindTime: '08:00', status: 'todo', countdownText: '' },
    //   { id: 2, time: '12:30', name: '二甲双胍缓释片', dose: '500mg/片 × 2片 餐前服用', remindTime: '12:30', status: 'done', countdownText: '' },
    //   { id: 3, time: '18:30', name: '辛伐他汀片', dose: '20mg/片 × 1片 睡前服用', remindTime: '18:30', status: 'warn', countdownText: '' },
    //   { id: 4, time: '23:59', name: '叶酸片', dose: '5mg/片 × 1片 餐后服用', remindTime: '23:59', status: 'todo', countdownText: '' }
    // ],
    medicines: [],
    statusObj: {
      0: '未打卡',
      1: '立即打卡',
      2: '已打卡',
      3: '漏服打卡',
      4: '超时打卡',
    },
    timer: null,
    // NFC相关数据
    showNFCModal: false,
    nfcDeviceInfo: {},
    nfcSupported: false,
    // NFC相关数据
    showNFCModal: false,
    nfcDeviceInfo: {},
    nfcSupported: false
  },

  onLoad() {
    this.checkAuthStatus();

    // 初始化NFC功能
    this.initNFC();
  },

  onShow() {
    this.checkAuthStatus();
    this.getRemindRecordToDay()
    // 设置当前页面到全局，用于NFC回调
    app.globalData.currentPage = this;
  },

  onUnload() {
    if (this.data.timer) clearInterval(this.data.timer)
  },

  // 检查授权状态
  checkAuthStatus: function () {
    const isAuthorized = app.globalData.isAuthorized;
    this.setData({
      isAuthorized
    });
  },

  // 获取手机号
  getPhoneNumber(e) {
    console.log(e, 22)
    if (e.detail.errMsg === "getPhoneNumber:ok") {
      const { encryptedData, iv, code } = e.detail;
      console.log(e.detail, 111)
      // wx.request({
      //   url: 'https://yourserver.com/decryptPhone',
      //   method: 'POST',
      //   data: { encryptedData, iv, code }, // 发送给后端解密
      // });
    }
  },

  // 处理用户登录
  handleUserLogin: function () {
    wx.showLoading({
      title: '登录中...'
    });

    app.userLogin().then((userInfo) => {
      wx.hideLoading();
      this.setData({
        isAuthorized: true
      });
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      });
    }).catch((err) => {
      wx.hideLoading();
      wx.showToast({
        title: '登录失败',
        icon: 'error'
      });
      console.error('登录失败:', err);
    });
  },

  // 初始化NFC功能
  initNFC: function () {
    const nfcSupported = app.globalData.nfcSupported;
    this.setData({
      nfcSupported
    });

    if (nfcSupported) {
      console.log('首页NFC功能已初始化');
    } else {
      console.log('当前设备不支持NFC功能');
    }
  },

  // 显示NFC设备信息（由app.js调用）
  showNFCDevice: function (deviceInfo) {
    this.setData({
      showNFCModal: true,
      nfcDeviceInfo: deviceInfo
    });
  },

  // 关闭NFC弹窗
  closeNFCModal: function () {
    this.setData({
      showNFCModal: false
    });
  },

  // 确认NFC设备
  confirmNFCDevice: function (e) {
    const deviceInfo = e.detail.deviceInfo;
    console.log('确认NFC设备:', deviceInfo);

    this.setData({
      showNFCModal: false
    });

    wx.showToast({
      title: '设备已确认',
      icon: 'success'
    });
  },

  // 显示NFC设备详情
  showNFCDetails: function (e) {
    const deviceInfo = e.detail.deviceInfo;
    console.log('查看NFC设备详情:', deviceInfo);

    // 显示详细信息
    wx.showModal({
      title: 'NFC设备详细信息',
      content: `设备ID: ${deviceInfo.id}\n设备类型: ${deviceInfo.type}\n原始数据: ${JSON.stringify(deviceInfo.rawData, null, 2)}`,
      showCancel: false,
      confirmText: '确定'
    });
  },

  openReminder() {
    const now = new Date()
    const hh = formatTimeUnit(now.getHours())
    const mm = formatTimeUnit(now.getMinutes())
    const ss = formatTimeUnit(now.getSeconds())
    this.setData({ showReminder: true, currentReminderTime: `${hh}:${mm}:${ss}` })
  },

  closeReminder() {
    this.setData({ showReminder: false })
  },

  noop() {},

  tapClock(e) {
    const { id } = e.currentTarget.dataset
    const targetMed = this.data.medicines?.find((m) => m.id === id)
    if (!targetMed) return
    if ([2, 4].includes(targetMed.status)) return
    if (targetMed.status == '3') { // 漏服打卡
      this.setData({ showMissModal: true, missMedicineId: id, missInput: '' })
      return
    } else if (targetMed.status == '1') {
      this.clockIn(id)
    }
    // const medicines = this.data.medicines?.map((m) => m.id === id ? { ...m, status: 'done' } : m)
    // this.setData({ medicines })
  },

  // 打卡
  async clockIn(id, reason) {
    const res = await clockIn(id, reason)
    console.log(res, 22)
    if (res) {
      wx.showToast({ title: '打卡成功', icon: 'success' })
      if (reason) {
        this.setData({ showMissModal: false, missMedicineId: null, missInput: '' })
      }
      const t = setTimeout(() => {
        this.getRemindRecordToDay()
        clearTimeout(t)
      }, 1500)
    }
  },

  onMissInput(e) {
    this.setData({ missInput: e.detail.value })
  },

  cancelMissReason() {
    this.setData({ showMissModal: false, missMedicineId: null, missInput: '' })
  },

  submitMissReason() {
    const reason = (this.data.missInput || '').trim()
    if (!reason) {
      wx.showToast({ title: '请填写漏服原因', icon: 'none' })
      return
    }
    const id = this.data.missMedicineId
    this.clockIn(id, reason)
    // const medicines = this.data.medicines?.map((m) => m.id === id ? { ...m, status: 'done', missReason: reason } : m)
    // this.setData({ medicines, showMissModal: false, missMedicineId: null, missInput: '' })
  },

  computeAllCountdowns: function () {
    const now = new Date()
    const updated = this.data.medicines?.map((item) => {
      const [hh, mm] = item.remindTime.split(':').map((v) => parseInt(v, 10))
      const remindTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hh, mm, 0)
      let diffMs = remindTime.getTime() - now.getTime()
      const overdue = diffMs < 0
      if (overdue) diffMs = Math.abs(diffMs)
      const hours = Math.floor(diffMs / 3600000)
      const minutes = Math.floor((diffMs % 3600000) / 60000)
      const seconds = Math.floor((diffMs % 60000) / 1000)
      const h = formatTimeUnit(hours)
      const m = formatTimeUnit(minutes)
      const s = formatTimeUnit(seconds)
      const prefix = overdue ? '时间已经过了' : '还剩'
      const text = `${prefix}${h}小时${m}分钟${s}秒`
      return { ...item, countdownText: text, overdue }
    })
    this.setData({ medicines: updated }, () => {
      clearInterval(this.data.timer)
      this.setData({ timer: this.data.timer })
    })
  },

  async getRemindRecordToDay() {
    const params = {
      userId: 1,
    }
    const res = await getRemindRecordToDay()
    this.setData({ medicines: res }, () => {
      this.computeAllCountdowns()
      const timer = setInterval(this.computeAllCountdowns, 1000)
      this.setData({ timer })
    })
    
  }
})


